package com.ht.api.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.util.HtUtil;
import com.ht.api.util.NoticeUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OpsTaskService {

    public static void refreshOpsTask (DataSource ds, StreamLoadConfig config, Entity opsTask) {
        JSONArray audienceRule = opsTask.getJSONArray("audience_rule");

        StringBuilder sql = new StringBuilder();
        sql.append("select ")
                .append("bitmap_to_string(bitmap_not(audienceusers.oneid, normalusers.oneid)) newids, ")
                .append("bitmap_to_string(bitmap_not(normalusers.oneid, audienceusers.oneid)) exitids ")
                .append("from ");

        sql.append("(").append("select bitmap_union(to_bitmap(oneid)) oneid from audience_relation where status = 0 and audience_id in (")
                .append(audienceRule.join(",")).append(") ").append(") audienceusers, ");

        sql.append("(").append("select bitmap_union(to_bitmap(oneid)) oneid from ops_tasks_users where status = 0 and task_id = ").append(opsTask.getMainId()).append(") normalusers ");

        Entity userIds = Db.findOne(ds, sql.toString());

        String newids = userIds.getStr("newids");
        String exitids = userIds.getStr("exitids");

        List<Entity> dataList = new ArrayList<>();
        String time = DateUtil.now();
        if (StrUtil.isNotBlank(newids)) {
            for (String oneid : newids.split(",")) {
                Entity opsTasksUsersLogs = Entity.create("ops_tasks_users_logs");
                opsTasksUsersLogs.set("oneid", oneid);
                opsTasksUsersLogs.set("task_id", opsTask.getMainId());
                opsTasksUsersLogs.set("time", time);
                opsTasksUsersLogs.set("status", 0);

                dataList.add(opsTasksUsersLogs);
            }
        }

        if (StrUtil.isNotBlank(exitids)) {
            for (String oneid : newids.split(",")) {
                Entity opsTasksUsersLogs = Entity.create("ops_tasks_users_logs");
                opsTasksUsersLogs.set("oneid", oneid);
                opsTasksUsersLogs.set("task_id", opsTask.getMainId());
                opsTasksUsersLogs.set("time", time);
                opsTasksUsersLogs.set("status", -1);

                dataList.add(opsTasksUsersLogs);
            }
        }

        Db.insertBatchWithStream(config, dataList);


        if (dataList.size() > 0) {//保存日志
            HtUtil.createLog(ds, opsTask.getMainId(), StrUtil.format("运营任务用户刷新数据：新增用户数-> %s，退出用户数-> %s",
                    StrUtil.isBlank(newids) ? 0 : newids.split(",").length, StrUtil.isBlank(exitids) ? 0 : exitids.split(",").length));
        }
    }


}
